<?php
namespace Kuoqi\DbDriver\Sql;
class Data{
	
	public $isCheckCol = true;//是否核验字符是否库中的
	
	private $columns = array();
	
	private $params = array();
	
	private $driver = null;
	
	public function __construct($driver){
		if($this->isCheckCol){
			//拉取数据库中当前表的字段信息
			$sqldriver = new Sql($driver);
			$query = $driver->query($sqldriver->scale('table-names'));
			$data = $query->fetchAll(\PDO::FETCH_ASSOC);
			$this->columns = array();
			foreach($data as $v){
				$this->columns[] = $v['col'];	
			}
		}
	}
	
	
	//初始化输入
	public function input($data){
		$this->inputInitData($data);//对传入的数据基本的处理
	}
	
	
	
	
	final function inputInitData($data){
		foreach($data as $k=>$v){
			if($this->isCheckCol){
				if(in_array($k,$this->columns)){
					$this->params[$k] = $this->inputCheckValue($v);		
				}
			}else{
				$this->params[$k] = $this->inputCheckValue($v);	
			}
		}
	}
	
	final function inputCheckValue($str){
		//todo--为了sql的安全，这里进行一定的处理
        $str = str_replace('\\','\\\\',$str);
        //对["]的处理
		$str = str_replace('"','\"',$str);
		return $str;
	}
	
	
	//输出处理区域
	public function output($withCode = true){
		if(!$this->params){
			throw new \Kuoqi\Error('INSERT 需要增加的内容不能完全为空');
		}
		$ns = array();
		$vs = array();
		foreach($this->params as $k=>$v){
			$ns[] = '`'.$k.'`';
			$vs[] = '"'.$v.'"';
		}
		$str = sprintf('(%s) VALUES (%s)',
			implode(',',$ns),
			implode(',',$vs)
		);
		return $str;
	}
	
	public function outputUpdate(){
		if(!$this->params){
			throw new \Kuoqi\Error('INSERT 需要增加的内容不能完全为空');
		}	
		$arr = array();
		foreach($this->params as $k=>$v){
			$arr[] = '`'.$k.'` = "'.$v.'"';
		}
		return implode(',',$arr);
	}
	
}